package com.fin.zw.intelligentbot.service;

import com.fin.zw.intelligentbot.model.session.SessionModel;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;

@Service("libraryFileService")
public class LibraryFileService {

    private static Logger logger = LoggerFactory.getLogger(LibraryFileService.class);

    /**
     * 文件上传处理
     * @param file
     * @param url
     * @param sessionModel
     * @throws IOException
     */
    public String saveFileLibrary(MultipartFile file, String url, SessionModel sessionModel) throws IOException {
        logger.info("开始上传语音库中文件："+file.getName());
        InputStream inputStream = file.getInputStream();
        File outFile = new File(url);
        if (!outFile.exists()) {
            outFile.mkdirs();
        }
        String path = new String();
        if(StringUtils.isNotEmpty(sessionModel.getCompanyCode())){
            path = url + sessionModel.getCompanyCode()+"/"+file.getName();
        }else{
            path = url + "admin/"+file.getName();
        }
        logger.info("文件上传的路径是："+path);
        File f = new File(path);
        if(!f.exists()){
            f.mkdir();
        }
        OutputStream ot = new FileOutputStream(f);
        byte[] buffer = new byte[1024];
        int len;
        while ((-1 != (len = inputStream.read(buffer)))) {
            ot.write(buffer, 0, len);
        }
        ot.close();
        inputStream.close();
        logger.info("文件上传结束。");
        return path;
    }

}
